<template>
    <page-wrap :header-props="headerProps"  :loading="loading">
        <template #extension>
            <div class="cm-order-header">
                <div class="cm-order-header-info">
                    <div class="cm-order-header-left">
                        <span class="cm-order-header__label">桌号：</span>
                        <span :class="['cm-order-header__value into',tableNumber?'cm-orange':'cm-gray']" @click="tableSelectShow = true">
                            {{ tableNumber?tableNumber:'选择桌位' }}
                        </span>
                    </div>
                    <div class="cm-order-header-right">
                        <div class="cm-order-header__tag">服务员：<span class="cm-order-header__lighthigh">{{appStore.user_info.userName}}</span></div>
                    </div>
                </div>
            </div>
            <z-search placeholder="请输入您要搜索的商品" @update:model-value="onUpdate"></z-search>
        </template>
        <div class="order-container">
            <z-sidebar :current-active="menuActive" :menu-list="configStore.signList" @click="onSidebar" />
            <div class="order-content-wrapper" ref="scrollContainer" @scroll="onScroll">
                <div class="order-content-wrapper-scroll">
                    <div class="cm-order-group" v-for="group, groupIndex in configStore.signList" :key="groupIndex">
                        <div class="cm-order-group-heading">
                            <div class="cm-order-group-title">{{group.name}}</div>
                            <div class="cm-order-group-subtitle" v-if="group.groupType == '1'">已送：{{group.usedValue}}/总额度:{{group.maxValue}}</div>
                            <div class="cm-order-group-subtitle" v-if="group.groupType == '2'">已送：{{group.usedValue}}/总份数:{{group.maxValue}}</div>
                        </div>
                        <div class="cm-order-group-listbox">
                            <ul class="cm-order-group-list">
                            <li class="cm-order-group-item" v-for="item, index in group.children" :key="index">
                                <div class="item-dish">
                                    <div class="item-dish-left" v-if="item.priceList">
                                        <img class="dish-left-img" :src="item.attachment" @error="$event.target.src = defutImage" />
                                        <div class="dish-left-over"
                                                v-if="!item.priceList.some(v => v.isEstmClear === '0' && v.state === '1') && item.priceList.some(v => v.state === '0')">
                                                <div class="dish-left-over__text">已下架</div>
                                        </div>
                                        <div class="dish-left-over"
                                                v-if="item.priceList.every((v) => v.state === '1') && item.priceList.every((v) => v.isEstmClear === '1')">
                                                <div class="dish-left-over__text">已沽清</div>
                                        </div>
                                        <img v-if="item.isUseGold == '1'" class="jinbi-img"
                                                src="https://oss.jtmckj.com/wmp/qnjg/signin/jinbi-h5.png" alt="">
                                    </div>
                                    <div class="item-dish-right">
                                        <div class="right-top">{{ item.goodsName }}</div>
                                        <!-- <div class="right-center"></div> -->
                                        <div class="right-bottom-left" v-if="item.priceList">
                                                <div class="left-title">权益会员价</div>
                                                <div class="left-value" v-if="item.type == 1 && item.priceList.length == 1 && !item.goodsFlavor">{{ formatNumber(item.priceList[0].vipPrice) }}</div>
                                                <div class="left-value" v-else>{{ formatNumber(item.vipPrice) }}</div>
                                        </div>
                                        <!-- <div class="right-price"><span class="icon">￥</span>{{ formatNumber(item.salePrice) }}</div> -->
                                        <div class="right-bottom" v-if="item.priceList">
                                            <!-- <div class="right-bottom-left">
                                                <div class="left-title">权益会员价</div>
                                                <div class="left-value">{{ formatNumber(item.vipPrice) }}</div>
                                            </div> -->
                                            <div class="right-price" v-if="item.type == 1 && item.priceList.length == 1 && !item.goodsFlavor"><span class="icon">￥</span >{{ formatNumber(item.priceList[0].salePrice) }}</div>
                                                <div class="right-price" v-else><span class="icon">￥</span >{{ formatNumber(item.salePrice) }}</div>
                                            <div class="right-bottom-right">
                                                <van-badge :content="item.showNum" :max='99' :showZero="false"
                                                    class="cm-van-badge" v-if="!(item.type == 1 && item.priceList.length == 1 && !item.goodsFlavor )">
                                                </van-badge>

                                                <div :class="{ 'cm-order-group__multiple': true, 'disabled': !item.priceList.some(v => v.isEstmClear === '0' && v.state === '1') }"
                                                    v-if="item.type == 2" @click="onHandleOrder('combo', item)">选套餐</div>
                                                <div :class="{ 'cm-order-group__multiple': true, 'disabled': !item.priceList.some(v => v.isEstmClear === '0' && v.state === '1') }"
                                                    v-if="(item.type == 1 && item.priceList.length > 1) || (item.type == 1 && item.goodsFlavor)"
                                                    @click="onHandleOrder('size', item)">选规格</div>
                                                <div class="cm-order-group__single"
                                                    v-if="item.type == 1 && item.priceList.length == 1 && !item.goodsFlavor " >
                                                    <z-stepper :min="0" v-model="item.num"
                                                        :show-minus="item.num == 0 ? false : true"
                                                        :show-input="item.num == 0 ? false : true"
                                                        :step="(item.num < item.saleLimitMin && item.saleLimitMin >= item.saleLimitStep) ? item.saleLimitMin : item.saleLimitStep"
                                                        :max="item.saleLimitMax"
                                                        :disabled="!item.priceList.some(v => v.isEstmClear === '0' && v.state === '1')"
                                                        disable-input @plus="onHandleOrder('plus', item)"
                                                        @minus="onHandleOrder('minus', item)" />
                                                </div>
                                            </div>
                                        </div>
                                        
                                    </div>
                                </div>
                                
                            </li>
                        </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="cm-order-footer">
                <div class="cm-order-footer-car" @click="onShowCart">
                    <van-badge :content="signStore.totalCount" :max='99' :showZero="false" class="cm-van-badge">
                    </van-badge>
                    <img class="cm-order-footer__icon" :src="img_icon_car">
                </div>
                <div class="cm-order-footer-info">
                    <div class="cm-order-footer__money">
                        <span class="cm-order-footer__rmb">￥</span>
                        <span class="cm-order-footer__num">{{formatNumber(signStore.totalAmount)}}</span>
                    </div>
                    <div class="cm-order-footer__quantity">共{{signStore.totalCount}}件</div>
                </div>
                <div class="cm-order-footer__control">
                    <z-button bold @click="onShowConfirmSign" v-has-role="'waiter-gift'">赠送</z-button>
                </div>
            </div>
        </template>
    </page-wrap>
    <!-- 规格选择 -->
    <SizeSelect v-model:show="sizeSelectShow" :data="sizeData" v-if="sizeSelectShow" source="sign" @join="onJoinSize"></SizeSelect>
    <!-- 套餐弹窗 -->
    <ComboSelect v-model:show="comboSelectShow" :data="comboData" @join="onJoinCombo"></ComboSelect>
    <!-- 购物车弹窗 -->
    <SignCart v-model:show="cartShow"></SignCart>
    <!-- 确认赠送弹出框 -->
    <z-dialog v-model:show="confirmSignshow" content="是否确认赠送 ？" @confirm="onConfirmSign"></z-dialog>
    <!-- 选择桌台组件 -->
    <!-- <TableSelect v-model:show="tableSelectShow" @close="onTableSelectClose" title="赠送下单" source="sign" line="2" state="2"></TableSelect> -->
    <TableSelectSpe
    v-model:show="tableSelectShow"
    @close="onTableSelectClose"
    title="赠送下单"
    source="save"
    line="2"
    state="2,3"
  ></TableSelectSpe>
</template>
<script setup>
import { showToast } from 'vant'
import { transformArrayProps,calculateOrderQty,formatNumber } from '@/lib/util.js'
import useConfigStore from '@/store/config'
import useSignStore from '@/store/sign'
import useAppStore from '@/store/app'
import Api from '@/api'
import _ from 'lodash'
import ls from '@/lib/ls'

import v_search_white from '@/assets/svg/common/v_search_white.svg'
import img_icon_car from '@/assets/images/open/img_icon_car.png'

const router = useRouter()
const configStore = useConfigStore()
const signStore = useSignStore()
const appStore = useAppStore()
//图片加载失败显示的默认图片
const defutImage = ref('https://oss.jtmckj.com/wmp/qnjg/signin/defutImage.png')
// 头部配置
const headerProps = {
    operation: [{
        type: 'text',
        v: '我的赠送',
        click() {
            router.push('/statistics/signorder')
        }
    }]
}
const tableNumber = ref(undefined)
const confirmSignshow = ref(false)
const menuActive = ref(0);

const postForm = reactive({
    consumeCode: '',
    roomCode: '',
    remark: '',
    detail: [],
    operType: '2'
})

// 选择桌台
const tableSelectShow = ref(false)
const onTableSelectClose = (type, args) => {
    tableSelectShow.value = false
    if (type == 'back') return
    const { roomName, roomCode } = args
    if (roomName) {
        tableNumber.value = args.roomName
        postForm.roomCode = args.roomCode
        postForm.consumeCode = args.consumeCode
    }
}

// 选套餐
const comboSelectShow = ref(false)
const onJoinCombo = (product) => {
    signStore.RefreshCart(product)
}

// 选规格
const sizeSelectShow = ref(false)
const onJoinSize = (product) => {
    // signStore.RefreshCart(product)
}

// 购物车
const cartShow = ref(false)
// 监听购物车商品变化
watch(()=>signStore.cartList, (nVal) => {
    // console.log('watch cart')
    // console.log(nVal)
    // 回填signList
    for (const product of configStore.signList) {
        for (const childItem of product.children) {
            childItem.showNum = 0;
        }
    }
    for (const cartItem of signStore.cartList) {
        const { goodsCode, groupCode } = cartItem;
        const productItem = configStore.signList.find(item => item.code === groupCode);
        if (productItem) {
            for (const childItem of productItem.children) {
                if (childItem.goodsCode === goodsCode) {
                    childItem.showNum += cartItem.num;
                }
            }
        }
    }
    for (const productItem of configStore.signList) {
        const { code } = productItem;
        const cartItems = signStore.cartList.filter(item => item.groupCode === code);
        productItem.badge = cartItems.reduce((sum, item) => sum + item.num, 0);
    }
    // 回填allSignList
    for (const product of configStore.allSignList) {
        for (const childItem of product.children) {
            childItem.showNum = 0;
        }
    }
    for (const cartItem of signStore.cartList) {
        const { goodsCode, groupCode } = cartItem;
        const productItem = configStore.allSignList.find(item => item.code === groupCode);
        if (productItem) {
            for (const childItem of productItem.children) {
                if (childItem.goodsCode === goodsCode) {
                    childItem.showNum += cartItem.num;
                    childItem.num = cartItem.num
                }
            }
        }
    }
    for (const productItem of configStore.allSignList) {
        const { code } = productItem;
        const cartItems = signStore.cartList.filter(item => item.groupCode === code);
        productItem.badge = cartItems.reduce((sum, item) => sum + item.num, 0);
    }

    // console.log(configStore.signList)
    // console.log(configStore.allSignList)

    // 购物车没商品情况下，关闭弹窗
    if (unref(cartShow) && !nVal.length) {
        cartShow.value = false
    }
}, { deep: true })

// 搜索商品
const onUpdate = function(val) {
    const matchingItems = [];
    configStore.allSignList.forEach((item) => {
        const clonedItem = { ...item }; // 克隆原始对象
        const children = item.children;
        const matchingChildren = children.filter((child) => {
            if (child.goodsName) {
                return child.goodsName.includes(val)
            } else {
                return child.goodName.includes(val)
            }
        });
        if (matchingChildren.length === 0) {
          return null;
        }
        clonedItem.children = matchingChildren;
        matchingItems.push(clonedItem);
    });
    configStore.signList = matchingItems
    // console.log(configStore.signList)
}

const sizeData = ref([])
const comboData = ref({})
const onHandleOrder = function(type, item) {
    // console.log('item')
    // console.log(item)
    if (!item.priceList.some(v => v.isEstmClear === '0' && v.state === '1')) return
    switch (type) {
        case 'combo':
            // const detail = item.priceList[0].detail
            // for (let i = 0; i < detail.length; i++) {
            //     const goodsDetail = detail[i].goodsDetail;
            //     detail[i].allNum = 0
            //     for (let j = 0; j < goodsDetail.length; j++) {
            //         const flavor = goodsDetail[j];
            //         flavor.isShowFlavor = true // 是否显示规格
            //         flavor.flavor = '' // 已选规格
            //         flavor.canPlus = false // 步进器是否可加
            //         flavor.stepNum = flavor.defaultQty // 步进器数量
            //         flavor.percentPrice = 0
            //         flavor.vipPercentPrice = 0
            //         // flavor.stepNum = '' 
            //         // console.log(flavor.goodsFlavor);
            //         for (let item of flavor.goodsFlavor) {
            //             item.active = false
            //             // // IsMultiple 0 单选 1多选
            //             // if (item.IsMultiple === "0") {  
            //             //     item.active = [0];
            //             // } else {
            //             //     item.active = 0;
            //             // }
            //         }
            //     }
            // }
            // comboData.value = item
            // comboSelectShow.value = true

            console.log(item);
            
            const detail = item.priceList[0].detail
            console.log(detail);
            for (let i = 0; i < detail.length; i++) {
                const goodsDetail = detail[i].goodsDetail;
                detail[i].allNum = 0
                for (let j = 0; j < goodsDetail.length; j++) {
                    const flavor = goodsDetail[j];
                    flavor.isShowFlavor = true // 是否显示规格
                    flavor.flavor = '' // 已选规格
                    flavor.canPlus = false // 步进器是否可加
                    flavor.stepNum = flavor.defaultQty // 步进器数量
                    flavor.percentPrice = 0
                    flavor.vipPercentPrice = 0
                    flavor.isSelect = false // 是否选中
                    flavor.choiceType = detail[i].choiceType
                    flavor.operType = detail[i].operType
                    // flavor.stepNum = '' 
                    // console.log(flavor.goodsFlavor);
                    if(flavor.goodsFlavor){
                        if(flavor.goodsFlavor.includes('[')){
                            flavor.goodsFlavor = JSON.parse(flavor.goodsFlavor)
                        }
                        for (let item of flavor.goodsFlavor) {
                            item.active = false
                            if(typeof item.FlavorStr == 'string'){
                        
                                const str = item.FlavorStr;
            
                                // 替换中文逗号为英文逗号
                                const normalizedStr = str.replace(/[，,]/g, ',');
                                // 使用英文逗号分隔字符串
                                const parts = normalizedStr.split(',');
                                // 将每个部分转换为对象
                                const result = parts.map(part => {
                                    // 默认值
                                    let uomName = part.trim();
                                    let addprice = 0;
                                    let select = false;
                                    // 检查是否有#，设置select
                                    if (uomName.includes('#')) {
                                        select = true;
                                        uomName = uomName.replace('#', '').trim();
                                    }
                                    // 检查是否有*，设置addprice
                                    const match = uomName.match(/\*(\d+)$/);
                                    if (match) {
                                        addprice = parseInt(match[1], 10);
                                        uomName = uomName.replace(match[0], '').trim();
                                    }
                                    return { uomName, addprice, select };
                                });
                                console.log(result);
                                
                                item.sizeList = result
                                
                            }
                        }
                        console.log(flavor.goodsFlavor);
                        
                    }
                    
                }
            }
            comboData.value = item
            comboSelectShow.value = true
            break;
            case 'size':
            const basicList = []
            basicList.push({
                type: "1",
                active: 0,
                title: '单位',
                isMultiple: '0',
                sizeList: item.priceList
            })
            console.log(basicList);
            let flavourList = []
            console.log(item);
            if (item.goodsFlavor) {
                flavourList = JSON.parse(item.goodsFlavor).map((v) => {
                    console.log(v.FlavorStr);
                    const flavourArr = [v.FlavorStr];
                    console.log(flavourArr);
                    return {
                        type: "2",
                        active: v.IsMultiple == 1 ? [0] : 0,
                        title: v.Name,
                        isMultiple: v.IsMultiple,
                        sizeList: flavourArr,
                    };
                });
            }
            const arr = basicList.concat(flavourList)
            console.log(arr);
            sizeData.value = {
                priceList: item.priceList,
                type: item.type,
                goodsType: item.goodsType,
                attachment: item.attachment,
                sizeGroup: arr
            }
            sizeData.value.sizeGroup.forEach((v, k) => {
                    console.log(v.sizeList);
                    
                    let list = v.sizeList
                    if(typeof list[0] == 'string'){
                        
                        const str = list[0];
    
                        // 替换中文逗号为英文逗号
                        const normalizedStr = str.replace(/[，,]/g, ',');
                        // 使用英文逗号分隔字符串
                        const parts = normalizedStr.split(',');
                        // 将每个部分转换为对象
                        const result = parts.map(part => {
                            // 默认值
                            let uomName = part.trim();
                            let addprice = 0;
                            let select = false;
                            // 检查是否有#，设置select
                            if (uomName.includes('#')) {
                                select = true;
                                uomName = uomName.replace('#', '').trim();
                            }
                            // 检查是否有*，设置addprice
                            const match = uomName.match(/\*(\d+)$/);
                            if (match) {
                                addprice = parseInt(match[1], 10);
                                uomName = uomName.replace(match[0], '').trim();
                            }
                            return { uomName, addprice, select };
                        });
                        console.log(result);
                        
                        v.sizeList = result
                        list = result
                        
                    }
                    let arr = []
                    list.forEach((vi,ki)=>{
                        if(vi.select){
                            arr.push(ki)
                        }
                    })
                    
                    if(arr.length == 1){
                        v.active = (v.isMultiple == 1 ? arr : arr[0])
                    }else if(arr.length > 1){
                        v.active = arr
                    }
                    
                })
                console.log(sizeData);
                
            sizeSelectShow.value = true
            break;
        case 'plus':
        case 'minus':
            const product = {
                mathType: type,
                type: item.type,
                num: item.num,
                attachment: item.attachment,
                flavor: '',
                groupCode: item.groupCode,
                ...item.priceList[0]
            }
            signStore.RefreshCart(product)
            break;
    }
}

watch([() => configStore.signList, () => configStore.allSignList], ([allSignList, signList]) => {
    // console.log('watch list')
    signList.forEach(group => {
        group.children.forEach(product => {
            if (product.priceList) {
                product.priceList.forEach(price => {
                    const totalSalePrice = parseFloat(price.salePrice) + parseFloat(group.groupUsedValue);
                    if (totalSalePrice > parseFloat(group.groupMaxValue)) {
                        price.isDisabledPlus = true;
                    } else {
                        price.isDisabledPlus = false;
                    }
                });
            }
        });
    });
    allSignList.forEach(group => {
        group.children.forEach(product => {
            if (product.priceList) {
                product.priceList.forEach(price => {
                    const totalSalePrice = parseFloat(price.salePrice) + parseFloat(group.groupUsedValue);
                    if (totalSalePrice > parseFloat(group.groupMaxValue)) {
                        price.isDisabledPlus = true;
                    } else {
                        price.isDisabledPlus = false;
                    }
                });
            }
        });
    });
}, { deep: true});

const onShowCart = function() {
    if (!signStore.cartList.length) return
    cartShow.value = !unref(cartShow)
}

const loading = ref(false)
// 赠送成功
const onConfirmSign = () => {
    loading.value = true

    const arr = _.cloneDeep(signStore.cartList)
    addIndex(arr)
    const newArr = []
    arr.forEach((obj) => {
        if (obj.hasOwnProperty('detail')) {
            obj.detail.forEach((detail) => {
                const newDetail = { ...detail, type: '3' };
                newArr.push(newDetail);
            });
            delete obj.detail;
        }
        newArr.push(obj);
    });
    newArr.reverse()
    postForm.detail = newArr.map((obj,k) => {
        console.log(obj);
        
        const { num, defaultQty, type, flavor, goodsPriceCode,itemCode,stepNum,choiceType,isSelect,operType} = obj
        const convertedObj = {
            ...obj,
        };
        convertedObj.itemCode = ''
        convertedObj.doType = 'add'
    
        if (flavor==undefined) {
            convertedObj.flavor = ''
        }
        if (itemCode!=undefined) {
            convertedObj.itemCode = itemCode
        }
        if (goodsPriceCode==undefined) {
            convertedObj.goodsPriceCode = ''
        }
        if (num !== undefined) {
            convertedObj.orderQty = num;
            delete convertedObj.num;
        }
        if (defaultQty !== undefined) {
            convertedObj.orderQty = defaultQty;
            delete convertedObj.defaultQty;
        }
        if (stepNum !== undefined) {
            convertedObj.orderQty = stepNum;
            delete convertedObj.stepNum;
        }
        if(choiceType == '1' && isSelect == false && operType == '0'){ // choiceType == '1' 是挑选种类  isSelect false 未选中 operType == '1'固定项目 不能修改配置
            convertedObj.orderQty = 0
            delete convertedObj.choiceType;
            delete convertedObj.isSelect;
        }
        if (type=='0'||type=='1') {
            convertedObj.itemType = '1'
        }
        if (type === '2') {
            convertedObj.flavor = ''
            convertedObj.itemType = '2'
            convertedObj.goodsPriceCode = convertedObj.goodsCode;
        }
        if (type === '3') {
            convertedObj.itemType = '3'
            convertedObj.goodsPriceCode = convertedObj.packageCode;
            delete convertedObj.packageCode;
        }

        delete convertedObj.mathType;
        delete convertedObj.type;
        delete convertedObj.attachment;
        delete convertedObj.orgCode;
        delete convertedObj.goodsFlavor;
        delete convertedObj.isEstmClear;
        delete convertedObj.mainAttachment;

        return convertedObj;
    });
    calculateOrderQty(postForm.detail)
    
    Api.Common.AppObjProcess.Do({
        "functionName": "orderAdd",
        "contentData": postForm
    }).then(res => {
        // console.log(res)
        showToast('赠送成功')
        confirmSignshow.value = false
        signStore.cartList.length = 0
        setZero(configStore.signList)
        setZero(configStore.allSignList)
        getSignPrice()
        loading.value = false
    }).catch(err=>{
        loading.value = false
    })
}
// 商品添加index 
const addIndex = (list)=>{
    list.forEach((item,index)=>{
        item.indexStr = index
        if(item.type == '2'){
            item.detail.forEach((v,k)=>{
                v.indexStr = index
            })
        }
    })
}
const setZero = (list)=>{
    for (const product of list) {
        for (const childItem of product.children) {
            childItem.showNum = 0;
            childItem.num = 0;
        }
    }
}

// 确认赠送弹窗
const onShowConfirmSign = function() {
    console.log(configStore.signList);
    
    if(configStore.signList.some(item => Number(item.usedValue) > Number(item.maxValue))){
        showToast('超出赠送额度')
        return
    }
    if (!postForm.roomCode) {
        showToast('请先选择桌号')
        return
    }
    if (!signStore.cartList.length) {
        showToast('请选择赠送商品')
        return
    }

    confirmSignshow.value = true
}

const onHandleSearch = function(val) {
    console.log('搜索关键词：', val)
}

// 初始化赠送列表
const getSignList = () => {
    const trans = [
        ['groupName', 'name'],
        ['groupCode', 'code'],
        ['groupGoods', 'children']
    ]
    const toolParent = JSON.parse(JSON.stringify(configStore.signCategoryList))
    console.log(toolParent);
    
    const parent = transformArrayProps(configStore.signCategoryList, trans)
    const child = configStore.goodsList;
    for (let i = 0; i < parent.length; i++) {
        const children = parent[i].children;
        for (let j = 0; j < children.length; j++) {
            const goodsCode = children[j].goodsCode;
            const matchingChild = child.find((item) => item.goodsCode === goodsCode);
            
            if (matchingChild) {
                if(!matchingChild.saleLimitMin || matchingChild.saleLimitMin == '0'){
                    matchingChild.saleLimitMin = 0
                }
                if(!matchingChild.saleLimitStep || matchingChild.saleLimitStep == '0'){
                    matchingChild.saleLimitStep = 1
                }
                if(!matchingChild.saleLimitMax || matchingChild.saleLimitMax == '0'){
                    matchingChild.saleLimitMax = 99999
                }
                children[j] = { ...children[j], ...matchingChild, num: 0, showNum: 0 };
                if(matchingChild.priceList){
                    matchingChild.priceList.forEach((vi,ki)=>{
                        if(!vi.saleLimitMin || vi.saleLimitMin == '0'){
                                vi.saleLimitMin = 0
                        }
                        if(!vi.saleLimitStep || vi.saleLimitStep == '0'){
                                vi.saleLimitStep = 1
                        }
                        if(!vi.saleLimitMax || vi.saleLimitMax == '0'){
                                vi.saleLimitMax = 99999
                        }
                    })
                }
            }
        }
    }
   
    
    
    // 过滤重复
    parent.forEach(entry => {
        const seen = new Set(); // 用于存储唯一组合
        entry.children = entry.children.filter(item => {
            const identifier = `${item.goodsCode}-${item.priceList}`; // 生成唯一标识符
            if (seen.has(identifier)) {
                return false; // 如果已存在，则过滤掉
            } else {
                seen.add(identifier); // 否则，添加到 Set 中
                return true; // 保留该对象
            }
        });
    });
    console.log(JSON.parse(JSON.stringify(parent)));
    console.log(toolParent);
    
    parent.forEach(item=>{
        if(item.children){
            item.children.forEach(v=>{
                if(v.priceList){
                    v.priceList = v.priceList.filter(vi => v.uomCodeback.includes(vi.uomCode));
                }
                
            })
        }
    })
  
    console.log(parent);


    configStore.signList = _.cloneDeep(parent)
    configStore.allSignList = _.cloneDeep(parent)

    // 备份数据
    configStore.toolSignList = _.cloneDeep(parent)
    configStore.toolallSignList = _.cloneDeep(parent) 

}
const signValue = ref({
    maxValue:'',
    usedValue:''
})
// 获取签送额度
const getSignPrice = async ()=>{
    Api.Common.AppObjProcess.Do({
    functionName: 'getSignGoodsList',
    contentData:{"userCode":appStore.user_info.userCode,"goodsName":""}
  })
    .then(res=>{
        console.log(JSON.parse(JSON.stringify(res)),'resprespresp');
        configStore.signCategoryList = JSON.parse(JSON.stringify(res.result).replaceAll('\\"', '"').replaceAll('"[', "[").replaceAll(']"', "]"))
        console.log(configStore.signCategoryList,'configStore.signCategoryList');
        configStore.signCategoryList.forEach(item=>{
                    if(item.groupGoods){
                        item.groupGoods = filterGoods(item.groupGoods);
                    }
        })
       
        
    })
}
function filterGoods(items) {
    const result = [];
    const uomMap = new Map();
  
    items.forEach(item => {
      const { goodsCode, uomCode } = item;
  
      // 检查 goodsCode 是否已存在于结果数组中
      if (!uomMap.has(goodsCode)) {
        // 如果不存在，将该元素添加到结果中，并初始化 uomCodeback
        result.push({ ...item, uomCodeback: [] });
        uomMap.set(goodsCode, result[result.length - 1]); // 记录在 uomMap 中
      } else {
        // 如果已存在，记录被过滤掉的 uomCode
        uomMap.get(goodsCode).uomCodeback.push(uomCode);
      }
    });
  
    // 在每个元素的 uomCodeback 中添加自己的 uomCode
    result.forEach(item => {
      item.uomCodeback.push(item.uomCode);
    });
  
    return result;
}
// 初始化
const onInit = async () => {
    await getSignPrice()
    getSignList()
  
}
onInit()

// 滚动联动
const scrollContainer = ref(null)
const onScroll = function() {
    const parentRect = unref(scrollContainer).getBoundingClientRect();
    // 获取所有锚点元素
    const navContents = document.querySelectorAll('.order-content-wrapper .cm-order-group')
    // 所有锚点元素的 offsetTop
    const offsetTopArr = []
    navContents.forEach((item) => {
        const childRect = item.offsetTop;
        const distance = Math.round(item.offsetTop - parentRect.top);
        offsetTopArr.push(distance);
    })
    // 获取当前文档流的 scrollTop
    const scrollTop = unref(scrollContainer).scrollTop
    // 定义当前点亮的导航下标
    let navIndex = 0
    for (let n = 0; n < offsetTopArr.length; n++) {
        // 如果 scrollTop 大于等于第 n 个元素的 offsetTop 则说明 n-1 的内容已经完全不可见
        // 那么此时导航索引就应该是 n 了
        if (scrollTop >= offsetTopArr[n]) {
            navIndex = n
        }
    }
    menuActive.value = navIndex
}
const onSidebar = function(code, k) {
    // console.log(code,k)
    const parentRect = unref(scrollContainer).getBoundingClientRect();
    // 获取目标的 offsetTop
    // css选择器是从 1 开始计数，我们是从 0 开始，所以要 +1
    const childRect = document.querySelector(`.order-content-wrapper .cm-order-group:nth-child(${k + 1})`)
    const distance = childRect.offsetTop - parentRect.top;
    const targetOffsetTop = Math.round(distance)
    scrollContainer.value.scrollTop = targetOffsetTop
}
</script>
<style scoped lang="scss">
.order-container {
    display: flex;
    height: 100%;
    overflow: hidden;

    .order-content-wrapper {
        padding: 0 11px;
        flex: 1;
        overflow-y: auto;

        &-scroll {
            overflow-y: auto;
        }

    }

    .cm-order-group__cover {
    .cm-order-group_img {
        position: relative;
        width: 100%;
        height: 120px;
        border-radius: 8px 8px 0px 0;
    }
   
}

}
.cm-order-footer-info{
    align-items: center;
}
.order-content-wrapper-scroll{
    overflow-y: auto;
    overflow-x: hidden;
}
.cm-order-footer__quantity{
    padding-left: 4px;
}
.item-dish{
    width: 100%;
    height: 100px;
    display: flex;
    align-items: center;
    background-color: #17171a;
    padding-bottom: 10px;
    border-bottom: 1px solid #2E2E2E;
    // justify-content: ;
    .item-dish-left{
        width: 100px;
        height: 100px;
        position: relative;
        .dish-left-img{
            width: 100px;
            height: 100px;
            border-radius: 4px;
        }
        .dish-left-over{
            width: 100px;
            height: 100px;
            background: #000000;
            opacity: 0.6;
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center;
            .dish-left-over__text{
                width: 60px;
                height: 30px;
                border-radius: 4px;
                border: 1px solid rgba($color: #FFFFFF, $alpha: 0.2);
                font-family: PingFang SC;
                font-weight: 500;
                font-size: 16px;
                color: #FFFFFF;
                line-height: 24px;
            }
        }
        .jinbi-img{
            width: 24px;
            height: 12px;
            background: #292933;
            border-radius: 4px 0px 3px 0px;
            position: absolute;
            bottom: 0;
            right: 0;
            color: #666666;
        }
        
    }
    .item-dish-right{
        width: 100%;
        height: 100px;
        padding-left: 8px;
        position: relative;
        .right-top{
            font-family: PingFang SC;
            font-weight: bold;
            font-size: 14px;
            color: #FFFFFF;
            line-height: 14px;
            padding-bottom: 8px;
            word-break: break-all;
            white-space: normal;
            margin-top: 10px;
        }
        .right-center{
            display: flex;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 12px;
            color: #999999;
            line-height: 12px;
            padding-bottom: 7px;
            word-break: break-all;
            white-space: normal;
        }
        .right-bottom-left{
                width: 110px;
                height: 18px;
                border-radius: 7px;
                border: 1px solid #666666;
                margin-top: 10px;
                display: flex;
                .left-title{
                    width: 55px;
                    font-family: PingFang SC;
                    font-weight: 800;
                    font-size: 10px;
                    color: #212121;
                    line-height: 14px;
                    background-color: #ffaa00;
                    border-radius: 7px 0 0 7px;
                    text-align: center;
                    padding-left: 4px;
                }
                .left-value{
                    width: 55px;
                    font-family: PingFang SC;
                    font-weight: 800;
                    font-size: 11px;
                    color: #FFFFFF;
                    line-height: 14px;
                    background-color: #404040;
                    text-align: center;
                }
            }

        .right-bottom{
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            position: absolute;
            width: 100%;
            bottom: 0;
            padding-right: 12px;
            margin-bottom: 6px;

            .right-price{
            font-family: PingFang SC;
            font-weight: 800;
            font-size: 18px;
            color: #FFFFFF;
            line-height: 18px;
            padding-bottom: 5px;
            .icon{
                font-size: 18px;
            }
            }
            
            .right-bottom-right{
               
            }
        }
    }
}
::v-deep(.van-stepper__minus:before){
    background: #212121 !important;
}
::v-deep(.van-stepper__minus:after){
    background: #212121 !important;
}
::v-deep(.van-stepper__minus){
    background: #FFAA00 !important;
}
::v-deep(.van-stepper__plus:before){
    background: #212121 !important;
}
::v-deep(.van-stepper__plus:after){
    background: #212121 !important;
}
::v-deep(.van-stepper__plus){
    background: #FFAA00 !important;
}
::v-deep(.z-sidebar){
    width: 64px !important;
}
</style>